package com.jihox.abookpro.domain;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

/**
 * 应用程序更新实体类
 */
public class Update implements Serializable{
	
	public final static String UTF8 = "UTF-8";
	public final static String NODE_ROOT = "oschina";
	
	private String versionCode;
	private String minSupportedVersion;
	private String downloadUrl;
	private String versionNotes;
	
	public String getVersionNotes() {
		return versionNotes;
	}
	public void setVersionNotes(String versionNotes) {
		this.versionNotes = versionNotes;
	}
	public String getMinSupportedVersion() {
		return minSupportedVersion;
	}
	public void setMinSupportedVersion(String minSupportedVersion) {
		this.minSupportedVersion = minSupportedVersion;
	}
	public String getVersionCode() {
		return versionCode;
	}
	public void setVersionCode(String versionCode) {
		this.versionCode = versionCode;
	}
	
	public String getDownloadUrl() {
		return downloadUrl;
	}
	public void setDownloadUrl(String downloadUrl) {
		this.downloadUrl = downloadUrl;
	}
	
	public static Update parse(InputStream inputStream) throws IOException, Exception {
		Update update = null;
        //获得XmlPullParser解析器
        XmlPullParser xmlParser = Xml.newPullParser();
        try {        	
            xmlParser.setInput(inputStream, UTF8);
            //获得解析到的事件类别，这里有开始文档，结束文档，开始标签，结束标签，文本等等事件。
            int evtType=xmlParser.getEventType();
			//一直循环，直到文档结束    
			while(evtType!=XmlPullParser.END_DOCUMENT){ 
		
	    		String tag = xmlParser.getName(); 
			    switch(evtType){ 
			    	case XmlPullParser.START_TAG:			    		
			            //通知信息
			            if(tag.equalsIgnoreCase("abookpro_android"))
			    		{
			            	update = new Update();
			    		}
			            else if(update != null)
			    		{
			    			if(tag.equalsIgnoreCase("version"))
				            {			      
			    				update.setVersionCode(xmlParser.nextText());
				            }
				            else if(tag.equalsIgnoreCase("minSupportedVersion"))
				            {			            	
				            	update.setMinSupportedVersion(xmlParser.nextText());
				            }else if(tag.equalsIgnoreCase("url"))
				            {			            	
				            	update.setDownloadUrl(xmlParser.nextText());
				            }else if(tag.equalsIgnoreCase("versionNotes"))
				            {			            	
				            	update.setVersionNotes(xmlParser.nextText());
				            }
			    		}
			    		break;
			    	case XmlPullParser.END_TAG:		    		
				       	break; 
			    }
			    //如果xml没有结束，则导航到下一个节点
			    evtType=xmlParser.next();
			}		
        } catch (Exception e) {
			throw e;
        } finally {
        	inputStream.close();	
        }      
        
        return update;       
	}
}
